﻿using System.Configuration;
using System.Configuration.Provider;
using System.Web.Configuration;

namespace ImageProvider
{
    // http://msdn.microsoft.com/en-us/library/aa479038.aspx

    public class ImageService
    {
        private volatile static ImageProviderBase provider;
        private static ImageProviderCollection providers;
        private static readonly object Lock = new object();

        static ImageService()
        {
            ImageService.LoadProviders();
        }

        public ImageProviderBase Provider
        {
            get { return ImageService.provider; }
        }

        public ImageProviderCollection Providers
        {
            get { return ImageService.providers; }
        }

        private static void LoadProviders()
        {
            // Avoid claiming lock if providers are already loaded
            if (ImageService.provider == null)
            {
                lock (ImageService.Lock)
                {
                    // Do this again to make sure provider is still null
                    if (ImageService.provider == null)
                    {
                        // Get a reference to the <imageService> section
                        var section = (ImageServiceSection)ConfigurationManager.GetSection("images");

                        // Load registered providers and point _provider to the default provider
                        ImageService.providers = new ImageProviderCollection();
                        ProvidersHelper.InstantiateProviders(section.Providers, ImageService.providers, typeof(ImageProviderBase));
                        ImageService.provider = ImageService.providers[section.DefaultProvider];
                    }
                }
            }

            if (ImageService.provider == null)
            {
                throw new ProviderException("Unable to load default ImageProvider");
            }
        }
    }
}